/**
 * @author yxw
 * date : 2013年10月4日 下午3:04:51 
 */
package com.tzinfo.tzt.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.galhttprequest.GalHttpRequest;
import com.galhttprequest.GalHttpRequest.GalHttpLoadTextCallBack;
import com.tzinfo.tzt.R;
import com.tzinfo.tzt.config.AppDataConfig;
import com.tzinfo.tzt.domain.HouseVillage;
import com.tzinfo.tzt.domain.MyResultList;
import com.tzinfo.tzt.util.JsonTools;

public class MyFabuSearchCommunityActivity extends BaseActivity implements
		OnItemClickListener {
	private EditText searchEditText;
	private TextView searchTextView;
	private RelativeLayout searchLayout;
	private ImageButton clearWordsBtn;

	private ListView listView;

	private List<Map<String, Object>> data;

	private SimpleAdapter simpleAdapter;

	// 标志
	private MyResultList result;

	static String sID = "sID";
	static String sName = "Name";
	private int pageNum = 1;
	private static final int pageSize = 10;
	GalHttpRequest galHttpRequest = new GalHttpRequest(this);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_community_search);
		mProgressBar = (ProgressBar) findViewById(R.id.progressbar_loding);
		init();
	}

	private void init() {
		galHttpRequest.setCacheEnable(false);
		searchEditText = (EditText) this.findViewById(R.id.et_search_top);
		searchEditText.addTextChangedListener(mTextWatcher);
		searchTextView = (TextView) this.findViewById(R.id.community_name);
		searchLayout=(RelativeLayout) this.findViewById(R.id.layout_of_community);
		clearWordsBtn=(ImageButton) this.findViewById(R.id.clear_words);
		listView = (ListView) findViewById(R.id.listview_search_result);
		listView.setOnItemClickListener(this);

	}

	TextWatcher mTextWatcher = new TextWatcher() {
		String text = "";

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
		}

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub

			text = searchEditText.getText().toString();
			if (text == null || "".endsWith(text)) {
				clearWordsBtn.setVisibility(View.GONE);
				searchLayout.setVisibility(View.GONE);
			} else {
				listView.setVisibility(View.GONE);
				searchTextView.setText("搜索“" + text + "”");
				searchLayout.setVisibility(View.VISIBLE);
				clearWordsBtn.setVisibility(View.VISIBLE);
			}
		}
	};

	/**
	 * 将得到的数据装载进ArrayList<Map<String, Object>>() data中
	 */
	private void setData() {
		if(data==null){
			data = new ArrayList<Map<String, Object>>();
		}else{
			data.clear();
		}
		HouseVillage item;
		Map<String, Object> map;
		for (int i = 0; i < result.getData().size(); i++) {
			item = (HouseVillage) result.getData().get(i);
			map = new HashMap<String, Object>();
			String strName = item.getName();
			if (strName.length() > 19) {
				strName = strName.substring(0, 19) + "…";
			}
			map.put(sName, strName);
			map.put(sID, item.getID());
			data.add(map);
		}
		if(simpleAdapter==null){
			simpleAdapter=new SimpleAdapter(this, data, R.layout.item_filter_content, 
					new String[]{sID,sName}, new int[]{R.id.id,R.id.text_filter_content});
			listView.setAdapter(simpleAdapter);
		}else{
			simpleAdapter.notifyDataSetChanged();
		}
		listView.setVisibility(View.VISIBLE);
	}

	private void getDataError(String ERRORMESSAGE) {
		new AlertDialog.Builder(this).setCancelable(false)
				.setMessage(ERRORMESSAGE)
				.setPositiveButton("知道了", new DialogInterface.OnClickListener()

				{
					public void onClick

					(DialogInterface dialog, int which) {
					}
				}).setNegativeButton(getResources().getString

				(R.string.try_again), new DialogInterface.OnClickListener()

				{
					public void onClick(

					DialogInterface dialogInterface, int

					whichButton) {
						showProgressBar();
						search();
					}
				}).show();
	}


	// onclick
	public void clearWords(View v) {
		searchEditText.setText(null);
	}

	public void searchCommunity(View v) {
		showProgressBar();
		searchLayout.setVisibility(View.GONE);
		search();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		TextView textView=(TextView) arg1.findViewById(R.id.id);
		TextView textView2=(TextView) arg1.findViewById(R.id.text_filter_content);
		Intent intent=new Intent();
		Log.e("communityId", textView.getText().toString());
		intent.putExtra("communityId", textView.getText().toString());
		intent.putExtra("community", textView2.getText().toString());
		setResult(1, intent);
		finish();
	}

	private void search() {
		pageNum = 1;
		// 通过线程访问网络得到数据
		String searchText = "";
		try {
			searchText = URLEncoder.encode(searchEditText.getText().toString(),
					"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String url=AppDataConfig.fabuUrl
				+ AppDataConfig.HouseVillage + "?skey=" + searchText;
		Log.e("url", url);
		galHttpRequest.setURL(url);
		galHttpRequest.startAsynRequestString(new GalHttpLoadTextCallBack() {

			@Override
			public void textLoaded(String arg0) {
				showResult(arg0);
			}
		});
	}

	// 显示结果
	private void showResult(String jsonString) {
		removeProgressBar();
		result = JsonTools.getHouseVillageResult(jsonString);
		if (result.getSuccess()) {
			setData();
		} else {
			getDataError("抱歉,没有搜索到小区");
		}
	}

}
